// Fill out your copyright notice in the Description page of Project Settings.
PRAGMA_DISABLE_OPTIMIZATION


#include "AnimSampleGameInstance.h"



void UAnimSampleGameInstance::Init()
{
	Super::Init();
	FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateUObject(this, &UAnimSampleGameInstance::Tick));
}

void UAnimSampleGameInstance::OnStart()
{
	Super::OnStart();
	TArray<TPair<FString, UObject*>> Arguments;
	Arguments.Add(TPair<FString, UObject*>(TEXT("GameInstance"), this));
	if(GetWorld()->GetNetMode() == NM_Client)
	{
		ClientGameScript = MakeShared<puerts::FJsEnv>(std::make_unique<puerts::DefaultJSModuleLoader>(TEXT("JavaScript")), std::make_shared<puerts::FDefaultLogger>(), 8080);
		ClientGameScript->WaitDebugger();
		ClientGameScript->Start("ClientTSMain", Arguments);
	}
	else if(GetWorld()->GetNetMode() == NM_DedicatedServer)
	{
		ServerGameScript = MakeShared<puerts::FJsEnv>(std::make_unique<puerts::DefaultJSModuleLoader>(TEXT("JavaScript")), std::make_shared<puerts::FDefaultLogger>(), 8080);
		ServerGameScript->WaitDebugger();
		ServerGameScript->Start("ServerTSMain", Arguments);
	}
	else
	{
		ClientGameScript = MakeShared<puerts::FJsEnv>(std::make_unique<puerts::DefaultJSModuleLoader>(TEXT("JavaScript")), std::make_shared<puerts::FDefaultLogger>(), 8081);
		// ClientGameScript->WaitDebugger();
		ServerGameScript = MakeShared<puerts::FJsEnv>(std::make_unique<puerts::DefaultJSModuleLoader>(TEXT("JavaScript")), std::make_shared<puerts::FDefaultLogger>(), 8080);
		// ServerGameScript->WaitDebugger();
		ClientGameScript->Start("ClientTSMain", Arguments);
		ServerGameScript->Start("ServerTSMain", Arguments);
	}
}

void UAnimSampleGameInstance::Shutdown()
{
	ENetMode NetMode = GetWorld()->GetNetMode();
	Super::Shutdown();
	if(NetMode == NM_Client)
	{
		ClientGameScript.Reset();
	}
	else if(NetMode == NM_DedicatedServer)
	{
		ServerGameScript.Reset();
	}
	else
	{
		ClientGameScript.Reset();
		ServerGameScript.Reset();
	}
}

bool UAnimSampleGameInstance::Tick(float DeltaTime)
{
	NotifyRegisterSelfDefinedTickFunction.ExecuteIfBound(DeltaTime);
	return true;
}

void UAnimSampleGameInstance::RegisterInteractionScriptFunctionByName(UObject* Object, FString DelegateName,
	FString FunctionName)
{
	if(Object == nullptr)
	{
		UE_LOG(LogProcess, Error, TEXT("Object is nullptr"));
		return;;
	}

	NotifyRegisterInteractionFunction.ExecuteIfBound(Object, DelegateName, FunctionName);
}
